package controller

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/wonderivan/logger"
	"net/http"
	"teresa/service"
)

var Node node

type node struct{}

func (n *node) GetNodes(ctx *gin.Context) {
	params := new(struct {
		FilterName string `form:"filtername"`
		Limit      int    `form:"limit"`
		Page       int    `form:"page"`
	})
	if err := ctx.Bind(params); err != nil {
		logger.Error(errors.New("Bind参数绑定失败," + err.Error()))
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "Bind参数绑定失败" + err.Error(),
			"data": nil,
		})
		return
	}
	dataList, err := service.Node.GetNodes(params.FilterName, params.Limit, params.Page)
	if err != nil {
		logger.Error(err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取node资源列表成功",
		"data": dataList,
	})
}

func (n *node) GetNodeDetail(ctx *gin.Context) {
	params := new(struct {
		NodeName string `form:"nodename"`
	})
	if err := ctx.Bind(params); err != nil {
		logger.Error(errors.New("Bind 绑定参数失败," + err.Error()))
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  errors.New("Bind 绑定参数失败," + err.Error()),
			"data": nil,
		})
		return
	}
	data, err := service.Node.GetNodeDetail(params.NodeName)
	if err != nil {
		logger.Error(err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var JsonNodeData Jsonnodedata
	jsonnodedata, err := json.Marshal(data)
	if err != nil {
		fmt.Println("数据转换失败",err.Error())
		return
	}
	err = json.Unmarshal(jsonnodedata, &JsonNodeData)
	if err != nil {
		fmt.Println("数据加载失败",err.Error())
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "获取node资源成功",
		"data": JsonNodeData,
	})
}
